package org.test.mq.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.test.mq.common.exception.AceMQException;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
/**
 * RocketMQ 消息发送者
 * @author tanjunyi
 * @time 2018-01-14
 */
public class AceMQConsumer {
	public static final Logger LOGGER = LoggerFactory.getLogger(AceMQProducer.class);
	DefaultMQPushConsumer consumer;
	private String groupName;
	private String namesrvAddr;
	private String topic;
	private String tag;
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	public String getNamesrvAddr() {
		return namesrvAddr;
	}
	public void setNamesrvAddr(String namesrvAddr) {
		this.namesrvAddr = namesrvAddr;
	}
	private IMessageProcessor processor;
	
	public void init() throws AceMQException{
		if(StringUtils.isBlank(this.groupName)) {
			throw new AceMQException("========= ERROR: groupName is blank ==========");
		}
		if(StringUtils.isBlank(this.topic)) {
			throw new AceMQException("========= ERROR: topic is blank ==========");
		}
		if(StringUtils.isBlank(this.namesrvAddr)) {
			throw new AceMQException(" ========== ERROR : nameSrvaddr is blank ========");
		}
		consumer = new DefaultMQPushConsumer(this.groupName);
		consumer.setNamesrvAddr(this.namesrvAddr);
        consumer.setInstanceName("Consumber");
        consumer.setVipChannelEnabled(false);
		
        try {
			consumer.subscribe(this.topic, this.tag);
			consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
			AceMessageListener aceMessageListener = new AceMessageListener();
			aceMessageListener.setMessageProcessor(this.processor);
			consumer.registerMessageListener(aceMessageListener);
			
			consumer.start();
			LOGGER.info("consumer is start,groupName:{},topic:{},nameservAddr:{}",groupName,topic,namesrvAddr);
		} catch (MQClientException e) {
			LOGGER.info(" xxxxxxxx consumer  start ERROR ,groupName:{},topic:{},nameservAddr:{}",groupName,topic,namesrvAddr,e);
			throw new AceMQException(" ===== ERROR: subscribe failed ，topic："+this.topic+"，tag:"+this.tag+"===========");
		}
	}
	public DefaultMQPushConsumer getConsumer() {
		return consumer;
	}
	public void setConsumer(DefaultMQPushConsumer consumer) {
		this.consumer = consumer;
	}
	public String getTopic() {
		return topic;
	}
	public void setTopic(String topic) {
		this.topic = topic;
	}
	public String getTag() {
		return tag;
	}
	public void setTag(String tag) {
		this.tag = tag;
	}
	public IMessageProcessor getProcessor() {
		return processor;
	}
	public void setProcessor(IMessageProcessor processor) {
		this.processor = processor;
	}
	public static Logger getLogger() {
		return LOGGER;
	}
	
}
